layui.define(['form','treeGrid'],function (exports) {
    var form = layui.form
        ,treeGrid = layui.treeGrid;
    var tableId = 'treeTable';
    var controller = {
        index:function () {
            treeGrid.render({
                elem: '#table-page'
                ,id:tableId
                ,method:'get'
                ,idField:'id'
                ,url: "index"
                ,toolbar: "#toolbar"
                ,defaultToolbar:[]
                ,treeId:'id'//树形id字段名称
                ,treeUpId:'parent_id'//树形父id字段名称
                ,treeShowName:'name'//以树形式显示的字段
                ,parseData: function(res){ //res 即为原始返回的数据
                    return {
                        "code": res.code, //解析接口状态
                        "msg": res.msg, //解析提示文本
                        "count": res.data.total, //解析数据长度
                        "data": res.data.list //解析数据列表
                    };
                }
                ,limit:0
                ,response: {
                    statusCode: 1 //规定成功的状态码，默认：0
                }
                ,cellMinWidth:100
                ,cols: [[
                    {fixed:'left', minWidth:10, type: 'checkbox'}
                    ,{field:'id', title: 'ID', sort: true}
                    ,{field:'name', title: '菜单名称'}
                    ,{templet:function (d) {
                        if(d.ParentMenu) {
                            return d.ParentMenu.name;
                        }
                        return '';
                        },title:'父菜单'}
                    ,{field:'url', title: 'url', minWidth:200}
                    ,{field:'icon',  title: '图标',templet: '<div><i class="layui-icon {{d.icon}}"></i></div>'}
                    ,{field:'sort', title: '排序'}
                    ,{field:'is_hide',title: '隐藏',templet:function (d) {
                            if(d.is_hide){
                                return '<input type="checkbox" name="post[is_hide]" value="1" data-id="'+d.id+'" checked lay-skin="switch" lay-filter="is_hide" lay-text="是|否">';
                            }
                            return '<input type="checkbox" name="post[is_hide]" value="1" data-id="'+d.id+'" lay-skin="switch" lay-filter="is_hide" lay-text="是|否">';
                        }}
                    ,{fixed: 'right', align:'center', toolbar: '#action', width:200}
                ]]
            });

            //监听工具条
            treeGrid.on('tool(table-page)', function(obj){ //注：tool 是工具条事件名，test 是 table 原始容器的属性 lay-filter="对应的值"
                var data = obj.data; //获得当前行数据
                var layEvent = obj.event; //获得 lay-event 对应的值（也可以是表头的 event 参数对应的值）
                var tr = obj.tr; //获得当前行 tr 的 DOM 对象（如果有的话）

                if(layEvent === 'add'){ //查看
                    controller.open_edit(data.id);
                } else if(layEvent === 'del'){ //删除
                    controller.delete_api(data.id);
                } else if(layEvent === 'edit'){ //编辑
                    controller.open_edit(data.id);
                } else if(layEvent === 'LAYTABLE_TIPS'){
                    layer.alert('Hi，头部工具栏扩展的右侧图标。');
                }
            });
            //监听事件
            treeGrid.on('toolbar(table-page)', function(obj){
                var checkStatus = treeGrid.checkStatus(obj.config.id);
                switch(obj.event){
                    case 'add':
                        controller.open_edit();
                        break;
                    case 'delete':
                        controller.delete_api(checkStatus.data);
                        break;
                    case 'update':
                        break;
                }
            });
            form.on('switch(is_hide)', function(data){
                var id = $(data.elem).data('id');
                var load_index = layer.load();
                $.post("status",{ids:[id],is_hide:data.elem.checked? 1 : 0})
                    .success(function (response) {
                        if(response.code){
                            notice.success(response.msg);
                        }else{
                            notice.error(response.msg);
                        }
                    })
                    .complete(function () {
                        layer.close(load_index);
                    });
            });
            form.on('submit(search-btn)',function (data) {
                treeGrid.reload(tableId,{
                    where: data.field
                });
                return false;
            });
        },
        open_edit:function (id = 0) {
            var url = '';
            var title;
            if(id){
                url = '/admin/admin_menu/edit/id/'+id;
                title = '编辑';
            }else{
                url = '/admin/admin_menu/add';
                title = '添加';
            }
            parent.layer.open({
                type:2
                ,title:title
                ,content:url
                ,area:['50%','80%']
                ,maxmin:true
                ,end:function () {
                    treeGrid.reload(tableId);
                }
            });
        },
        add:function(){
            controller.edit();
        },
        edit:function () {
            var IconFonts = layui.IconFonts;
            //图标选择器
            IconFonts.render({
                // 选择器，推荐使用input
                elem: '#icon', //选择器ID
                // 数据类型：fontClass/layui_icon，
                type: 'layui_icon',
                // 是否开启搜索：true/false
                search: true,
                // 是否开启分页
                page: true,
                // 每页显示数量，默认12
                limit: 12,
                // 点击回调
                click: function (data) {
                }
            });
            var icon = $("#icon").val();
            if(icon){
                /**
                 * 默认选选中图标
                 */
                IconFonts.checkIcon("icon",icon,"layui_icon");
            }

            /* 监听提交 */
            form.on('submit(submit-form)', function(data){
                var load_index = layer.load();
                $.post($("form[lay-filter=edit-form]").get(0).action,data.field)
                    .success(function (response) {
                        if(response.code){
                            notice.success(response.msg);
                            setTimeout(function () {
                                parent.layer.closeAll();
                            },1000);
                        }else{
                            notice.error(response.msg);
                        }
                    })
                    .complete(function () {
                        layer.close(load_index);
                    });
                return false;
            });

        },
        delete_api:function (data) {
            layer.confirm("您真的要删除吗？",function (index) {
                layer.close(index);
                var ids = [];
                if(data instanceof Array){
                    layui.each(data,function (k,item) {
                        ids.push(item.id);
                    });
                }else{
                    ids = [data];
                }
                var load_index = layer.load();
                $.post("delete",{ids:ids})
                    .success(function (response) {
                        if(response.code){
                            notice.success(response.msg);
                            setTimeout(function () {
                                treeGrid.reload(tableId);
                            },1000);
                        }else{
                            notice.error(response.msg);
                        }
                    })
                    .complete(function () {
                        layer.close(load_index);
                    });
            });
        }
    };
   exports('admin_admin_menu',controller)
});